package com.qf.gateway.filter;

import com.qf.gateway.service.TenantService;
import com.qf.gateway.utils.EncryptUtil;
import com.qf.gateway.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 认证过滤器, 第三方接口中心对接,  租户系统, 管理系统都要经过这个认证过滤器
 * @author 千锋健哥
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private TenantService tenantService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2. 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //3. 获取请求访问的uri路径
        String path = request.getURI().getPath();
        //4. 判断访问路径如果是租户注册, 租户登录, 租户验证码, 租户退出, 管理员所有, 路径无条件放行
        if (path.contains("/user") ||
                path.contains("/auth/tenant/login") ||
                path.contains("/auth/tenant/regist") ||
                path.contains("/auth/checkcode/send") ) {
            return chain.filter(exchange);
        }

        /**
         * 5. 判断是第三方业务系统访问路径, 那么在这里进行鉴权操作
         */
        if(path.contains("/api")) {
            //5.1 从请求头中获取accessKey, 获取AccessSecurit秘钥, sign签名
            String accessKey = request.getHeaders().getFirst("access-key");
            String accessSecurit = request.getHeaders().getFirst("access-securit");
            String sign = request.getHeaders().getFirst("sign");

            try {
                //5.2 判断key, 秘钥, 签名不为空
                if (!StringUtils.isEmpty(accessKey)
                        && !StringUtils.isEmpty(accessSecurit)
                        && !StringUtils.isEmpty(sign)) {
                    //5.3 根据key和秘钥算出来签名的明文内容
                    String signTemp = accessKey + accessSecurit;

                    //5.4. 校验请求头中的签名和加密后的签名是否正确
                    boolean valid = EncryptUtil.valid(signTemp, sign);
                    if (valid) {
                        //5.5. 如果签名正确, 校验accessKey和accessSecurity秘钥
                        Boolean flag = tenantService.findByAccessKeyAndSecurit(accessKey, accessSecurit);
                        //5.6 如果accessKey和accessSecurity秘钥正确, 那么将accessKey放入当前请求头中放行
                        if (flag) {
                            request.mutate().header("token", accessKey);
                            return chain.filter(exchange);
                        }

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                //抛出权限不足401状态码
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

        }

        /**
         * 6. 判断访问路径是租户系统访问路径, 那么在这里进行鉴权操作
         */
        String token = request.getHeaders().getFirst("token");
        if (!StringUtils.isEmpty(token)) {
            try {
                Claims claims = JwtUtil.parseJWT(token);
                String tenantId = claims.getSubject();
                //在当前请求头中, 加入当前登录租户的租户id
                request.mutate().header("token", tenantId);
                //当前请求放行
                return chain.filter(exchange);
            } catch (Exception e) {
                //如果抛出异常, 是正常现象, 因为jwt可能过期, 也可能被转改
            }
        }

        //7. 其他情况抛出401权限不足异常提示信息
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
